package com.awcall.iot.controller;

import com.awcall.iot.common.BaseController;
import com.awcall.iot.common.ResponseResult;
import com.awcall.iot.model.OperateLog;
import com.awcall.iot.model.Role;
import com.awcall.iot.model.SystemUser;
import com.awcall.iot.model.UserProject;
import com.awcall.iot.service.*;
import com.awcall.iot.utils.JwtUtils;
import com.awcall.iot.utils.RequestUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/admin")
public class LoginController extends BaseController {

    @Autowired
    private ISystemUserService iSystemUserService;

    @Autowired
    private IOperateLogService iOperateLogService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private ISettingService iSettingService;

    @Autowired
    private IUserProjectService iUserProjectService;

    @RequestMapping("/login")
    public ResponseResult login(@RequestBody SystemUser systemUser) {
        if (StringUtils.isEmpty(systemUser.getUsername())) {
            return new ResponseResult(1, "用户名为空");
        }
        if (StringUtils.isEmpty(systemUser.getPassword())) {
            return new ResponseResult(2, "密码为空");
        }

        Wrapper<SystemUser> wrapper = new EntityWrapper<SystemUser>()
                .eq(SystemUser.USERNAME, systemUser.getUsername())
                .last("LIMIT 1");
        SystemUser systemUser1 = iSystemUserService.selectOne(wrapper);
        if (systemUser1 == null) {
            EntityWrapper<SystemUser> systemUserEntityWrapper = new EntityWrapper<>();
            systemUserEntityWrapper.eq("telephone",systemUser.getUsername());
            SystemUser systemUser2 = iSystemUserService.selectOne(systemUserEntityWrapper);
            if (systemUser2 == null){
                return new ResponseResult(3, "用户不存在");
            }else {
                systemUser1 = systemUser2;
            }
        }
        if (!DigestUtils.md5Hex(systemUser.getPassword()).equals(systemUser1.getPassword())) {
            return new ResponseResult(4, "密码错误");
        }
        if (1 == systemUser1.getStatus()) {
            return new ResponseResult(5, "账户已禁用");
        }
        if (null == systemUser1.getRoleId()) {
            return new ResponseResult(6, "用户没有权限");
        }
        systemUser1.setToken(JwtUtils.sign(systemUser1.getId()));

        EntityWrapper<Role> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(Role.ID, systemUser1.getRoleId());
        Role role = roleService.selectOne(entityWrapper);
        systemUser1.setRoleName(role.getRoleName());

        EntityWrapper<UserProject> userProjectEntityWrapper = new EntityWrapper<>();
        userProjectEntityWrapper.eq(UserProject.USER_ID,systemUser1.getId()).setSqlSelect(UserProject.PROJECT_ID);
        List<Object> objects = iUserProjectService.selectObjs(userProjectEntityWrapper);
        systemUser1.setObjects(objects);

        String company = iSettingService.getValue("COMPANY");

        systemUser1.setCompanyName(company);

        OperateLog operateLog = new OperateLog();
        operateLog.setCreatedAt(new Date())
                .setSystemUserId(systemUser1.getId())
                .setType(1)
                .setIp(RequestUtils.getIp())
                .setSystemUserName(systemUser1.getUsername())
                .setDescription("登录");
        iOperateLogService.insert(operateLog);

        return new ResponseResult<>(systemUser1);
    }

    @PostMapping("/loginByToken")
    public ResponseResult loginByToken() {
        SystemUser systemUser = iSystemUserService.selectById(getSystemUserId());
        if (systemUser == null) {
            return new ResponseResult(1, "账号不存在");
        }

        int systemUserstatus = 2;
        if (systemUser.getStatus() == systemUserstatus) {
            return new ResponseResult(2, "账号已禁用");
        }

        if (null == systemUser.getRoleId()) {
            return new ResponseResult<>(3, "账号无权限");
        }
        systemUser.setToken(JwtUtils.sign(systemUser.getId()));

        EntityWrapper<Role> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(Role.ID, systemUser.getRoleId());
        Role role = roleService.selectOne(entityWrapper);
        systemUser.setRoleName(role.getRoleName());

        EntityWrapper<UserProject> userProjectEntityWrapper = new EntityWrapper<>();
        userProjectEntityWrapper.eq(UserProject.USER_ID,systemUser.getId()).setSqlSelect(UserProject.PROJECT_ID);
        List<Object> objects = iUserProjectService.selectObjs(userProjectEntityWrapper);
        systemUser.setObjects(objects);

        String company = iSettingService.getValue("COMPANY");

        systemUser.setCompanyName(company);

        OperateLog operateLog = new OperateLog();
        operateLog.setCreatedAt(new Date())
                .setSystemUserId(systemUser.getId())
                .setType(1)
                .setIp(RequestUtils.getIp())
                .setSystemUserName(systemUser.getUsername())
                .setDescription(systemUser.getUsername() + "登录了");
        iOperateLogService.insert(operateLog);

        return new ResponseResult<>(systemUser);
    }

}
